class BlogController < ApplicationController
  before_filter :login?, :except=>[:show]
  after_filter :post_log
  layout "main"

  def destroy_blog
    @blog= Blog.find params[:blog_id]
    @user= @blog.user
    Post.destroy_all :user_id=>@user.id
    @blog.destroy
    flash[:notice]= "ลบบล็อกเรียบร้อยแล้ว"
    redirect_to :action => "show_all"
  end
  def ban_blog
    @user= User.find params[:user_id]
    # @todo still have bug here, posts not deleted ??
#    Post.destroy_all :user_id=>@user.id
    @user.blog.destroy
    @user.update_attribute("ban_blog", true)
    redirect_to :action => "show_all"
  end
  def show_all
    if params[:q].blank?
      @posts = Post.paginate :order=>'created_at DESC', :per_page=>10, :page=>params[:page]
    else
      c= "subject LIKE '%#{params[:q]}%' OR body LIKE '%#{params[:q]}%' "
      @posts = Post.paginate :conditions=>c, :order=>'created_at DESC', :per_page=>10, :page=>params[:page]
    end
  end
  def new
    if current_user.has_blog?
      redirect_to :action=>:show, :user=>current_user.login
    end
    @blog= Blog.new
  end
  def create
    @blog= Blog.new params[:blog]
    @blog.user_id= current_user.id
    if @blog.save
      flash[:notice]= "สร้างบล็อกเรียบร้อยแล้ว"
      redirect_to :action => "show", :user=>current_user.login
    else
      flash[:notice]= "ขออภัย ไม่สามารถสร้างบล็อกได้ กรุณาตรวจสอบการใส่ข้อมูล"
      render :action=>"new"
    end
  end
  def edit
    redirect_to_root unless current_user.has_blog?
    @blog= Blog.find_by_user_id session[:user_id]
  end
  def delete_photo
    @blog= Blog.find params[:id]
    @blog.blog_photo.destroy
#    @blog.save
    redirect_to :action => "edit"
  end
  def update
    @blog= Blog.update params[:blog][:id], params[:blog]
    flash[:notice]= "แก้ไขบล็อกเรียบร้อยแล้ว"
    redirect_to :action => "show"
  end
  def show
    if params[:user]
      @user = User.find_by_login params[:user], :include=>[:posts]
    else
      @user = current_user
    end
    @blog= @user.blog
    if @blog
      @posts = Post.paginate :conditions=>['user_id = ?', @user.id],
       :order=>'created_at DESC', :per_page=>10, :page=>params[:page]
    else
      flash[:notice]= "ขออภัย ไม่สามารถค้นหาบล็อกดังกล่าวได้"
      redirect_to :action => "show_all"
    end
  end
  def add_post
    @post = Post.new
  end
  def destroy_post
    @post = Post.find params[:id]
    @post.destroy
    flash[:notice]= "ลบเรียบร้อยแล้ว"
    redirect_to :action => "show"
  end
  def add_photo
    @post = Post.new
  end
  def add_widget
    @post = Post.new
  end
  def create_post
    @post = Post.new params[:post]
    @post.user_id= current_user.id
    @post.blog_id= current_user.blog.id
    @post.save
    flash[:notice]= "เพิ่มบล็อกเรียบร้อยแล้ว"
    redirect_to :action => "show"
  end
end
